<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>对props限制</title>
  </head>

  <body>
    <div id="test"></div>
    <div id="test2"></div>
    <div id="test3"></div>

    <script type="text/javascript" src="../js/react.development.js"></script>
    <script
      type="text/javascript"
      src="../js/react-dom.development.js"
    ></script>
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <script type="text/javascript" src="../js/prop-types.js"></script>

    <script type="text/babel">
      class Person extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
           
          };
        }

        render() {
          //props是只读的
				  //this.props.name = 'jack' //此行代码会报错，因为props是只读的
          const {name,age,sex} = this.props;
          return (
            <ul>
              <li>姓名:{name}</li>
              <li>年龄:{age}</li>
              <li>性别:{sex}</li>
            </ul>
          );
        }
      }
      //对标签属性进行类型、必要性的限制
      Person.propTypes = {
        name:PropTypes.string.isRequired, //限制name必传，且为字符串
        sex:PropTypes.string,//限制sex为字符串
        age:PropTypes.number,//限制age为数值
        speak:PropTypes.func,//限制speak为函数
      } 
      //指定默认标签属性值
      Person.defaultProps = {
        sex:'不男不女',//sex默认值为不男不女
        age:18 //age默认值为18
      }
      const p = {name:'老刘',age:12,sex:'男'}

      function speak() {
        console.log('我说话了');
      }

      ReactDOM.render(<Person  {...p} speak={speak}/>, document.getElementById("test"));
      ReactDOM.render(<Person  name='jerry' />, document.getElementById("test2"));
      ReactDOM.render(<Person  name='tom' age={18} sex='女'/>, document.getElementById("test3"));
    </script>
  </body>
</html>
